package com.hdhere.core.security.shiro.filter;

import com.hdhere.core.security.shiro.AccessResponse;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/*******************************************************************************************
 * 自定义授权认证，及无权限处理
 *
 * @author: dustin
 * @date: 2019-08-15 12:36
 * @Description:
 * @version 1.0
 *
 *******************************************************************************************
 */
public class MyPermsFilter extends AuthorizationFilter {

    private static final Logger log = LoggerFactory.getLogger(FormAuthenticationFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = this.getSubject(request, response);
        String[] perms = (String[])((String[])mappedValue);
        boolean isPermitted = true;
        if (perms != null && perms.length > 0) {
            if (perms.length == 1) {
                if (!subject.isPermitted(perms[0])) {
                    isPermitted = false;
                }
            } else if (!subject.isPermittedAll(perms)) {
                isPermitted = false;
            }
        }

        return isPermitted;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {

//        if (log.isTraceEnabled()) {
//            log.trace("Attempting to access a path which requires authentication.  Forwarding to the "
//                    + "Authentication url [" + getLoginUrl() + "]");
//        }
        Subject subject = getSubject(request, response);
        if (subject.getPrincipal() == null)
            saveRequestAndRedirectToLogin(request, response);
        else
            AccessResponse.onDenied(request, response);

        return false;
    }

}
